/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-11-5      SummerGift   first version
 */
 
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <fal.h>



#include "easyflash.h"
/* defined the LED0 pin: PF7 */

#define LED0_PIN    GET_PIN(E, 15)


static int easyflash_sample(void)
{
    /* fal init */
    fal_init();

    /* easyflash init */
    if(easyflash_init() == EF_NO_ERR)
    {
		char *c_old_boot_times;
		c_old_boot_times = ef_get_env("boot_times");
        /* get the boot count number failed */
        if (c_old_boot_times == RT_NULL)
		{
			rt_kprintf("reset ENV !\n");
			ef_env_set_default();
		}
           
        uint32_t i_boot_times = NULL;
        char c_new_boot_times[11] = {0};

        /* get the boot count number from Env */
        c_old_boot_times = ef_get_env("boot_times");
        /* get the boot count number failed */
        if (c_old_boot_times == RT_NULL)
            c_old_boot_times[0] = '0';

        i_boot_times = atol(c_old_boot_times);
        /* boot count +1 */
        i_boot_times ++;
        rt_kprintf("===============================================\n");
        rt_kprintf("The system now boot %d times\n", i_boot_times);
        rt_kprintf("===============================================\n");
        /* interger to string */
        sprintf(c_new_boot_times, "%d", i_boot_times);
        /* set and store the boot count number to Env */
        ef_set_env("boot_times", c_new_boot_times);
        ef_save_env();
    }
	
	return RT_EOK;
}
INIT_ENV_EXPORT(easyflash_sample);

int main(void)
{
    int count = 1;
    /* set LED0 pin mode to output */
    rt_pin_mode(LED0_PIN, PIN_MODE_OUTPUT);
	
	rt_pin_mode(GET_PIN(D, 8), PIN_MODE_OUTPUT);
	rt_pin_mode(GET_PIN(D, 9), PIN_MODE_OUTPUT);
	rt_pin_write(GET_PIN(D, 8), PIN_HIGH);
	rt_pin_write(GET_PIN(D, 9), PIN_HIGH);

	rt_thread_mdelay(500);

	GPIO_InitTypeDef GPIO_InitStruct = {0};
	__HAL_RCC_USART3_CLK_DISABLE();
  
    /**USART3 GPIO Configuration    
    PD8     ------> USART3_TX
    PD9     ------> USART3_RX 
    */
    HAL_GPIO_DeInit(GPIOD, GPIO_PIN_8|GPIO_PIN_9);
	__HAL_RCC_USART3_CLK_ENABLE();
    __HAL_RCC_GPIOD_CLK_ENABLE();
	__HAL_AFIO_REMAP_USART3_ENABLE();
    /**USART3 GPIO Configuration    
    PD8     ------> USART3_TX
    PD9     ------> USART3_RX 
    */
    GPIO_InitStruct.Pin = GPIO_PIN_8;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_9;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

    while (count++)
    {
        rt_pin_write(LED0_PIN, PIN_HIGH);
        rt_thread_mdelay(500);
        rt_pin_write(LED0_PIN, PIN_LOW);
        rt_thread_mdelay(500);
		//rt_kprintf("tets\n");
    }

    return RT_EOK;
}


